package fractal.model;

public class ColorPalette {

	private int size;
	private int palette[];

	public ColorPalette() {
		this.initPalette(0, 0, 0);
	}

	public ColorPalette(int r, int g, int b) {
		this.initPalette(r, g, b);
	}

	private void initPalette(int r, int g, int b) {
		this.size = 256;
		this.palette = new int[this.size];
		this.setPalette(r, g, b);
	}

	public void setPalette(int r, int g, int b) {
		int mr = 1, ar = 0, r0;
		int mg = 1, ag = 0, g0;
		int mb = 1, ab = 0, b0;

		if (r < 128) {
			mr = -1;
			ar = 255;
			r = 255 - r;
		}
		if (g < 128) {
			mg = -1;
			ag = 255;
			g = 255 - g;
		}
		if (b < 128) {
			mb = -1;
			ab = 255;
			b = 255 - b;
		}

		for (int i = 0; i < 256; i++) {
			r0 = (ar + mr * i) * r / 255;
			g0 = (ag + mg * i) * g / 255;
			b0 = (ab + mb * i) * b / 255;

			this.palette[i] = this.getColorRGB(r0, g0, b0);
		}
	}

	public int getColorNr(int nr) {
		return this.palette[nr];
	}

	public int getColorRGB(int r, int g, int b) {
		return 0xff000000 | ((r & 255) << 16) | ((g & 255) << 8) | (b & 255);
	}
}
